#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Script to parse login.guiguider file and extract specified fields.
"""

import json
import sys


def filter_frontjson(frontjson_data):
    """
    过滤FrontJson数据，只保留必要的字段。
    """
    filtered_data = []
    for screen in frontjson_data:
        filtered_screen = {
            "name": screen.get("name"),
            "type": screen.get("type"),
            "list": []
        }
        
        if "list" in screen:
            for item in screen["list"]:
                # 只保留必要的字段
                filtered_item = {
                    "name": item.get("name"),
                    "type": item.get("type"),
                    "left": item.get("left"),
                    "top": item.get("top"),
                    "width": item.get("width"),
                    "height": item.get("height"),
                    "text": item.get("text"),
                    "img_path": item.get("img_path"),
                    "rotate": item.get("rotate"),
                    "x": item.get("x"),
                    "y": item.get("y")
                }
                
                # 为imgbtn类型添加额外的图片路径字段
                if item.get("type") == "imgbtn":
                    filtered_item["src_released"] = item.get("src_released", "")
                    filtered_item["src_pressed"] = item.get("src_pressed", "")
                    filtered_item["src_checked_released"] = item.get("src_checked_released", "")
                    filtered_item["src_checked_pressed"] = item.get("src_checked_pressed", "")
                
                # 保留style数组
                if "style" in item:
                    # 只保留指定字段
                    filtered_style = []
                    for style_item in item["style"]:
                        # 跳过state为LV_STATE_DISABLED的节点
                        if style_item.get("state") == "LV_STATE_DISABLED":
                            continue
                        new_style_item = {
                            "part": style_item.get("part"),
                            "state": style_item.get("state"),
                            "disable": style_item.get("disable"),
                            "font": style_item.get("font"),
                            "text_align": style_item.get("text_align"),
                        }
                        # 移除值为None的字段
                        new_style_item = {k: v for k, v in new_style_item.items() if v is not None}
                        filtered_style.append(new_style_item)
                    filtered_item["style"] = filtered_style
                    # 解析style数组中state为LV_STATE_DEFAULT的条目
                    for style_item in filtered_style:
                        if style_item.get("state") == "LV_STATE_DEFAULT":
                            filtered_item["font"] = style_item.get("font")
                            filtered_item["text_align"] = style_item.get("text_align", "LV_TEXT_ALIGN_CENTER")
                            break  # 只取第一个匹配的条目
                
                # 移除值为None的字段
                filtered_item = {k: v for k, v in filtered_item.items() if v is not None}
                filtered_screen["list"].append(filtered_item)
        
        # 移除值为None的字段
        filtered_screen = {k: v for k, v in filtered_screen.items() if v is not None}
        filtered_data.append(filtered_screen)
    
    return filtered_data


def extract_fields(data):
    """
    从数据中提取所需字段。
    """
    result = {}
    
    # 提取 projectSettings
    if 'projectSettings' in data:
        result['projectSettings'] = data['projectSettings']
    
    # 提取 keyBoard
    # if 'Application' in data and 'keyBoard' in data['Application']:
    #     result['keyBoard'] = data['Application']['keyBoard']
        
    # 提取 resolution
    if 'projectSettings' in data and 'resolution' in data['projectSettings']:
        result['resolution'] = data['projectSettings']['resolution']
        
    # # 提取 ImportFonts 的下一子项
    # if 'ImportFonts' in data:
    #     result['ImportFonts'] = data['ImportFonts']
        
    # 保留并过滤 FrontJson 结构
    if 'FrontJson' in data:
        result['FrontJson'] = filter_frontjson(data['FrontJson'])
            
    return result


def parse_guiguider(input_file, output_file):
    """
    Parse the guiguider file and save extracted data to output file.
    Additionally, save each screen in FrontJson to a separate JSON file.
    """
    try:
        with open(input_file, 'r', encoding='utf-8') as f:
            data = json.load(f)
        
        extracted_data = extract_fields(data)
        
        # 保存主JSON文件
        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(extracted_data, f, ensure_ascii=False, indent=2)
        
        # 为FrontJson中的每个screen创建单独的JSON文件
        if 'FrontJson' in extracted_data:
            import os
            json_dir = os.path.join(os.path.dirname(output_file), 'json')
            os.makedirs(json_dir, exist_ok=True)
            
            for screen in extracted_data['FrontJson']:
                screen_name = screen.get('name')
                if screen_name:
                    screen_file_path = os.path.join(json_dir, f'{screen_name}.json')
                    with open(screen_file_path, 'w', encoding='utf-8') as f:
                        json.dump(screen, f, ensure_ascii=False, indent=2)
        
        print(f"Successfully parsed {input_file} and saved to {output_file}")
        print(f"Individual screen files saved to {os.path.join(os.path.dirname(output_file), 'json')} directory")
    except FileNotFoundError:
        print(f"Error: File {input_file} not found.")
        sys.exit(1)
    except json.JSONDecodeError as e:
        print(f"Error: Failed to decode JSON from {input_file}: {e}")
        sys.exit(1)
    except Exception as e:
        print(f"Error: {e}")
        sys.exit(1)


if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: python parse_guiguider.py <input_file> <output_file>")
        sys.exit(1)
    
    input_file = sys.argv[1]
    output_file = sys.argv[2]
    
    parse_guiguider(input_file, output_file)